package mse.eai.esb;

import java.io.StringReader;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import messageObjects.LotteryGameObj;

import org.jboss.logging.Logger;
import org.jboss.soa.esb.actions.ActionLifecycle;
import org.jboss.soa.esb.actions.ActionLifecycleException;
import org.jboss.soa.esb.helpers.ConfigTree;
import org.jboss.soa.esb.message.Message;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class ParseLottery implements ActionLifecycle {

	private static final Logger log = Logger.getLogger(ParseLottery.class);

	@Override
	public void destroy() throws ActionLifecycleException {
		// TODO Auto-generated method stub

	}

	@Override
	public void initialise() throws ActionLifecycleException {
		// TODO Auto-generated method stub

	}

	public ParseLottery(ConfigTree config) {

	}

	public Message process(Message m) {
		log.info("ESB Action start ------>");

		try {

			log.info("ParseLottery");
			String xml = (String) m.getBody().get(
					"org.jboss.soa.esb.message.defaultEntry");

			InputSource inputSource = new InputSource(new StringReader(xml));

			XPath xPath = XPathFactory.newInstance().newXPath();

			// XPathExpression
			// xPathExpression=xPath.compile("/catalog/journal/article[@date='January-2004']/title");
			// String title = xPathExpression.evaluate(inputSource);

			String expression = "//return";
			NodeList nodes = (NodeList) xPath.evaluate(expression, inputSource,
					XPathConstants.NODESET);

			int gameId = 0;
			String gameDate = "";

			log.info("Parsing lottery"); // in " + xml);

			for (int i = 0; i < nodes.getLength(); i++) {

				Node node = nodes.item(i);
				Node drawDayNode = (Node) xPath.evaluate("drawDay", node,
						XPathConstants.NODE);

				gameDate = drawDayNode.getTextContent();

				Node idNode = (Node) xPath.evaluate("id", node,
						XPathConstants.NODE);

				gameId = Integer.parseInt(idNode.getTextContent());

			}

			LotteryGameObj game = new LotteryGameObj(gameId, gameDate);

			m.getBody().add("lottery", game);

			log.info("<------- ESB Action done");
			return m;

		} catch (Exception e) {
			e.printStackTrace();
			log.info("<------- ESB Action done");
			return m;
		}
	}

}
